function throttle<T extends (...args: any[]) => void>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let lastInvokeTime = 0;
  return function (...args: Parameters<T>): void {
    const now = Date.now();

    if (now - lastInvokeTime >= delay) {
      func(...args);
      lastInvokeTime = now;
    }
  };
}

function debounce<T extends (...args: any[]) => void>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: NodeJS.Timeout;

  return function (...args: Parameters<T>): void {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(() => {
      func(...args);
    }, delay);
  };
}

// 获取地址栏query的参数 '/detail?id=xxx'
const getUrlParams = (paramName: string): string | null => {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(paramName);
}
// 允许提交文件扩展名白名单
const extensionList = ["pdf", "txt", "doc", "docx", "png", "jpg", "jpeg", "webp", "gif", "zip", "rar", '7z', "md", "mp4",]
// 允许提交文件扩展名
const allowFilePass = (filename: string): boolean => {
  return extensionList.includes(getFileExtension(filename))
}

// 获取文扩展名
export const getFileExtension = (filename: string): string => {
  let parts = filename.split('.');
  return parts[parts.length - 1].toLowerCase();
}
const getStorage = (key:string)=>{
  const storage = localStorage.getItem(key)
  if(storage){
    let storageOb = JSON.parse(storage)
    if((new Date().getTime()-storageOb.timestamp)>3600*24){
      return null
    }else{
      return storageOb['value']
    }
  }else{
    return null
  }
}
const setStorage = (key: string, val: any)=>{
  let ob = {
    timestamp:new Date().getTime(),
    value:val
  }
  localStorage.setItem(key,JSON.stringify(ob))
}
const uuid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    // eslint-disable-next-line no-mixed-operators
    let r = (Math.random() * 16) | 0,
      // eslint-disable-next-line no-mixed-operators
      v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
/*
* @desc:判断dom是否在视野范围内
* */
function isElementInViewport(element:HTMLElement) {
  let rect = element.getBoundingClientRect();
  return (
    rect.top <= window.innerHeight && // 元素顶部在视口内或刚刚出现在视口中
    rect.bottom >= 0                // 元素底部在视口内或刚刚从窗口上边划过去
  );
}


export {
  throttle,
  debounce,
  getUrlParams,
  allowFilePass,
  getStorage,
  setStorage,
  uuid,
  isElementInViewport
};
